#include "login.h"
#include <mysql.h>
#include <jcode.h>
#include <formsetdatabase.h>
#include "ui_login.h"
#include <QDebug>
#include <QMessageBox>
#include <QFile>
#include <mainwindow.h>
#include <QMovie>
#include <QButtonGroup>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDir>

QSqlDatabase mySQL::cn = QSqlDatabase::addDatabase("QMYSQL");
QString mySQL::UserName="";
QString mySQL::TypeId="";

QString mySQL::ServerMySQL="";
QString mySQL::DataBasePort="3306";
QString mySQL::UpFileURL="";
QString mySQL::DataBaseName="";
QString mySQL::DataBaseUserName="";
QString mySQL::DataBasePassWord="";
QString mySQL::ServerWEB="";

QString mySQL::ND="2020";
QString mySQL::SendString="";
QString mySQL::Permission="";
QString mySQL::SYDW="";
QString mySQL::PZQR="";
QString mySQL::CPUID="";
QString mySQL::MACadd="";
bool OpenDatabase()
{

    //数据库驱动类型为SQL Server
    mySQL::cn.setHostName(mySQL::ServerMySQL);      //连接数据库主机名，这里需要注意（若填的为”127.0.0.1“，出现不能连接，则改为localhost)
    mySQL::cn.setPort(mySQL::DataBasePort.toInt());                 //连接数据库端口号，与设置一致
    mySQL::cn.setDatabaseName(mySQL::DataBaseName);      //连接数据库名，与设置一致
    mySQL::cn.setUserName(mySQL::DataBaseUserName);          //数据库用户名，与设置一致
    mySQL::cn.setPassword(mySQL::DataBasePassWord);    //数据库密码，与设置一致
    mySQL::cn.open();
    if(!mySQL::cn.open())                                      //打开数据库
    {
        qDebug()<<mySQL::cn.lastError().text();
        QMessageBox::critical(0, QObject::tr("打开数据库失败！！"), mySQL::cn.lastError().text());
        return false;                                   //打开失败
    }
    else
    {
        //qDebug()<<"打开数据库成功!";

    }
    return true;
}
bool Widget::LoadSysINFO(){
    QString SQL="";
    QSqlQuery query(mySQL::cn);
    SQL=QString("SELECT info FROM systeminfo where type_id='%1' and type='系统参数'").arg(mySQL::TypeId);
    QString INI="";
    QString str="";
    query.exec(SQL);
    while(query.next()){
        str=query.value("info").toString().trimmed();
    }
    //QMessageBox::warning(this,"警告",str);
    query.clear();
    if (str.left(1)=="{"){
        QJsonObject obj;
        obj=JCode::QStringTOQJson(str); //JSON转
        QString tmpstr=obj["SYDW"].toString();        
        mySQL::SYDW=tmpstr;
        tmpstr=obj["PZQR"].toString();
        mySQL::PZQR=tmpstr;
    }
    return true;
}
bool Widget::LoadINI(){
    QString curPath= QCoreApplication::applicationDirPath();//获取当前目录
    QString iniFile=QString("%1/conDataBase.ini").arg(curPath);
    QString str=JCode::OpenText(iniFile);
    str=str.replace("\n","");

    if (str!=""){
        //读取出了文件后直接代开数据库
        str=JCode::toXOR(str,'J'); //解密
        QJsonObject obj;
        obj=JCode::QStringTOQJson(str); //转JSON
        mySQL::ServerMySQL=obj["DataBaseServer"].toString();
        mySQL::DataBasePort=obj["DataBasePort"].toString();
        mySQL::UpFileURL=obj["UpFileURL"].toString();
        mySQL::DataBaseName=obj["DataBaseName"].toString();
        mySQL::DataBaseUserName=obj["DataBaseUserName"].toString();
        mySQL::DataBasePassWord=obj["DataBasePassWord"].toString();
        ui->cmbUser->clear();
        if(OpenDatabase()){

            QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
            query.exec("SELECT username FROM  users order by type_id");
            while(query.next()){
                ui->cmbUser->addItem(query.value("username").toString());
            }
            QString SQL="";
            SQL="SELECT nd FROM  nd ";
            SQL+=" order by nd desc ";
            ui->cmbND->clear();
            query.exec(SQL);
            while(query.next()){
                ui->cmbND->addItem(query.value("nd").toString());
            }
            query.clear();
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //this->move(400,400);
    this->show();
    this->setWindowTitle("财务辅助系统登录");

    //mySQL::CPUID=JCode::GetCPUID();
    mySQL::MACadd=JCode::GetMACadd();
    //QMessageBox::critical(0, "系统信息", JCode::SYSINFO());
    ui->txtPws->setEchoMode(QLineEdit::Password); //设置密码输入框
    QString curPath= QCoreApplication::applicationDirPath();//获取当前目录
    QString gifname = QString("%1/logo.gif").arg(curPath);

    if (JCode::isFileExist(gifname)==false) //文件不存在就下载文件
    {
        QString url="http://jinesc.cn/zb_users/upload/2020/12/202012101607582307549973.gif";
        setNetworkGIF(url);
    }else{
        //存在就直接打开文件
        QMovie *movie = new QMovie( gifname); //path是gif图片的绝对路径
        movie->setScaledSize(ui->labGif->size());
        ui->labGif->setMovie(movie);
        movie->start();
    }

    bool setBase=LoadINI();
    if (setBase==false){
        //没有读取到配置文件 打开配置文件的界面
        QMessageBox::critical(0, "数据库连接失败！", "数据库连接失败！进入连接数据库设置！");
        FormSetDataBase * formSet=new class FormSetDataBase;
        formSet->show();
        connect(formSet,SIGNAL(sendData(QString)),this,SLOT(LoadINI()));
        //this->close();
    }
    //点击登录按钮的信号槽
    connect(ui->btnLogin,&QPushButton::clicked,[=](){
        QString PWS=ui->txtPws->text();
        QString User=ui->cmbUser->currentText();
        QString SQL="";
        QString type_id="";
        if (PWS==""){
            QMessageBox::critical(0, "密码输入错误", "密码不得为空！！！");
        }else{
            ui->btnLogin->setEnabled(false);
            SQL.append("SELECT password,type_id,permission FROM  users where username='");
            SQL.append(User);
            SQL.append("' order by user_id ");
            QSqlQuery query(mySQL::cn); //查询
            query.exec(SQL);
            QString sPWS="";
            QString  Permission="";
            //这里用了循环，也就是说万一有多条记录只认最后一条记录。
            while(query.next()){
                sPWS=query.value("password").toString();
                //sPWS 为BASE64编码 解码过程：
                QByteArray text = sPWS.toLocal8Bit();
                sPWS = text.fromBase64(text);
                type_id=query.value("type_id").toString();
                Permission=query.value("permission").toString();
            }

            query.clear();
            if(sPWS==PWS){
               //QMessageBox::information(this,"提示信息","密码校验成功！");
               //打开新的窗口 在隐藏自己
               mySQL::UserName=User;
               mySQL::TypeId=type_id;
               mySQL::ND=ui->cmbND->currentText();
               mySQL::Permission=Permission;
               //qDebug() << mySQL::TypeId;
               LoadSysINFO();//读取保存数据库里的系统信息
               MainWindow * mainWindows = new MainWindow;
               mainWindows->show();
               this->close();
            }else{
               QMessageBox::warning(this,"警告","密码校验失败！");
            }
            ui->btnLogin->setEnabled(true);
        }

    });
}
void Widget::setNetworkGIF(const QString &GifUrl)
{
   QUrl url(GifUrl);
   QNetworkAccessManager manager;
   QEventLoop loop;

   // qDebug() << "图片下载地址： " << GifUrl;
   QNetworkReply *reply = manager.get(QNetworkRequest(url));
   //请求结束并下载完成后，退出子事件循环
   QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
   //开启子事件循环
   loop.exec();
   QByteArray gifmsg = reply->readAll();
   QString curPath= QCoreApplication::applicationDirPath();//获取当前目录
   QString gifname = QString("%1/logo.gif").arg(curPath);
       QFile file(gifname);
       if(!file.open(QFile::WriteOnly))
       {
           qDebug() << "open file fail";
           exit(1);
       }
       file.write(gifmsg);
       file.close();
   QMovie *movie = new QMovie( gifname); //path是gif图片的绝对路径
   movie->setScaledSize(ui->labGif->size());
   ui->labGif->setMovie(movie);
   movie->start();
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_cmbUser_currentTextChanged(const QString &arg1)
{
   QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
   QString SQL="";
   SQL=QString("SELECT nd.nd FROM  nd left join users  on  nd.type_id=users.type_id where users.username='%1' order by nd.nd desc ").arg(arg1);
   query.exec(SQL);
   ui->cmbND->clear();
   while(query.next()){
       ui->cmbND->addItem(query.value("nd").toString());
   }

}

void Widget::on_btnSetDataBase_clicked()
{
    FormSetDataBase * formSet=new class FormSetDataBase;
    formSet->show();
    connect(formSet,SIGNAL(sendData(QString)),this,SLOT(LoadINI()));
}
